#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
from ofc2 import *


def is_holiday(dat):
    if isinstance(dat, str):
        dat = date(*map(int, dat.split("-")))
    if dat.weekday() in (5, 6):
        return True
    return False


_rulers = []
for i in (1, 10, 100, 1000, 10000, 100000, 1000000):
    _rulers.extend(map(lambda x: x*i, [1, 2, 3, 4, 5, 6, 8]))
#_rulers = (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000)
def get_ruler(value):
    for ruler in _rulers:
        if ruler >= value:
            return ruler


#colors = ["#3030d0", "#56acde", "#23ecae"]
colors = ["#6d23a7", "#ff6600", "#3170c2", "#ff0000", "#92b53d", "#3030d0", "#56acde", "#23ecae"]
components = [bar_glass, line, bar_stack]
class OFC(open_flash_chart):
    def __init__(self, *args, **kw):
        open_flash_chart.__init__(self, *args, **kw)
        self.ruler = 10
        self.right_ruler = 1
        self.color_id = 0
        self.component = 0
        self.vlines = []
        self.nvlines = 1
        self.nlabels = 15

    def setLabels(self, lst):
        labels = []
        for i, e in enumerate(lst):
            if not isinstance(e, date):
                labels.append(e)
                continue
            if is_holiday(e):
                labels.append({"text": e.strftime("%d"), "colour": "#ff0000"})
            else:
                labels.append({"text": e.strftime("%d")})
            if e.day == 1:
                self.vlines.append((i, u"%d月"%e.month))
        length = len(labels)
        self.nvlines = length / 30 + 1
        if length > self.nlabels:
            sep = int(length/self.nlabels)
            def div_test(n, label):
                if (n%sep)==0:
                    return label
                return ''
            self.component = 1
            labels = [div_test(i, label) for i, label in enumerate(labels)]
        elif length < self.nlabels:
            labels.extend(['']*(self.nlabels-length))
        self.x_axis.labels.labels = labels

    def setYLegend(self, text):
        self.y_legend = y_legend(text=text, style="{font-size:20px}")

    def addRightYAxis(self, min, max, steps):
        self.y_axis_right = y_axis_right(min=min, max=max, steps=steps)

    def addBar(self, text, values, component=None, right=False):
        vmax = max(0, 0, *filter(lambda v: isinstance(v, (int, long, float)), values))
        if right:
            right_ruler = max(self.right_ruler, get_ruler(vmax))
            self.right_ruler = right_ruler
            self.y_axis_right.max = right_ruler
            self.y_axis_right.steps = right_ruler/5.0
        else:
            ruler = max(self.ruler, get_ruler(vmax))
            self.ruler = ruler
            self.y_axis.max = ruler
            self.y_axis.steps = ruler/5

        color_id = self.color_id
        self.color_id += 1
        if component is None:
            component = components[self.component]
        else:
            component = components[component]
        b = component()
        b.dot_style = hollowdot(halo_size=0, width=3, dot_size=3, color=colors[color_id])
        b.values = values
        b.color = colors[color_id]
        b["text"] = text
        b["font-size"] = 12
        if right:
            b["axis"] = "right"
        self.add_element(b)

    def addBarStack(self, texts, values):
        self.y_axis.max = self.ruler
        self.y_axis.steps = self.ruler/5
        b = bar_stack()
        b.values = values
        b.keys = [{"colour": colors[i], "text": texts[i], "font-size": 13} for i in range(len(texts))]
        b.colours = colors[:len(texts)]
        self.add_element(b)

    def addPie(self, values):
        p = pie(alpha=0.6)
        p.values = values
        p.colours = colors[:len(values)]
        self.add_element(p)

    def addTags(self, values):
        self.add_element({"type": "tags", "values": values})

    def addShape(self, values):
        s = shape()
        s.colour = "#94500d"
        s.values = values
        self.add_element(s)

    def addVerticalLine(self, x):
        #yl, yh = -10000, 10000
        yl, yh = 0, self.y_axis.max
        w = 0.02 * self.nvlines
        self.addShape([dict(x=x-w,y=yl), dict(x=x-w,y=yh), dict(x=x+w,y=yh), dict(x=x+w,y=yl)])

    def addVLines(self):
        for i, s in self.vlines:
            self.addVerticalLine(i)
        w = 0.02 * self.nvlines
        self.addTags([{"x": i+w, "y": self.y_axis.max/2, "text": s, "align-x": "right"} for i, s in self.vlines])


def makeChart(text):
    chart = OFC()
    chart.x_axis = x_axis(labels=labels(labels=[]))
    chart.title = title(text=text)
    chart.y_axis = y_axis(min=0, max=10, steps=2)
    chart.setYLegend("")
    return chart
